package com.zsl.service.impl;

import com.zsl.dao.UsersDao;
import com.zsl.dao.impl.UsersDaoImpl;
import com.zsl.model.Users;
import com.zsl.service.UsersService;
import com.zsl.util.ListToJSON;

import java.util.List;
import java.util.Map;

public class UsersServiceImpl implements UsersService {
    private final UsersDao userDao = new UsersDaoImpl();//依赖注入

    @Override
    public boolean isReallyUsers(String uname, String pwd) {
        return userDao.getUserByName(uname, pwd) != null;
    }

    @Override
    public Map<String, String> getUserTableJson(String[] query) throws Exception {
        int rows = Integer.parseInt(query[0]);
        int page = Integer.parseInt(query[1]);
        System.out.println(rows + " " + page);
        //获取分页后的列
        String sql = "SELECT * FROM users WHERE is_deleted=0 LIMIT " + (page - 1) * rows + "," + page * rows;
        List<Users> users = userDao.queryBySQL(sql);
        Map<String, String> map = ListToJSON.UsersListToJSON(users);
        map.put("total", userDao.getAllUserNum());
        return map;
    }

    @Override
    public void deleteUserByUidService(int uid) throws Exception {
        int line = userDao.deleteUserByUid(uid);
        if (line == 0) {
            throw new Exception("删除失败");
        }
    }

    @Override
    public void addUserService(Users user) throws Exception {
        // dao
        try {
            userDao.addUser(user);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception();
        }
    }

    @Override
    public void updateUserInfo(Users user) throws Exception {
        int line = userDao.UpdateUserInfo(user);
        if (line == 0) {
            throw new Exception();
        }
    }

    //TODO 实现
    @Override
    public Map<String, String> getUsersBySearchStr(String searchStr) throws Exception {
        List<Users> users = userDao.getUsersBySearchStr(searchStr);
        return ListToJSON.UsersListToJSON(users);
    }
}
